import React, {useEffect, useState} from "react";
import {PageContainer, ProForm, ProFormDateRangePicker, ProFormTreeSelect} from "@ant-design/pro-components";
import {Col, DatePicker, message, Row, TreeDataNode} from "antd";
import {getDepartmentMembers, getDepartments} from "@/services/department/department";
import {getGroups} from "@/services/group/group";
import {getRedPacketStatistics} from "@/services/redpacket/redpacket";
import {getAllAudios} from "@/services/audio/audio";
import {useModel} from "@@/exports";
import {ProFormDateTimeRangePicker} from "@ant-design/pro-form";

const {RangePicker} = DatePicker;

const RedPacketStatistics: React.FC = () => {
  const {initialState, setInitialState} = useModel('@@initialState');

  const formRef = React.useRef();
  const audioFormRef = React.useRef();

  const [departments, setDepartments] = useState([])
  const [sales, setSales] = useState([])
  const [wechatGroups, setWechatGroups] = useState([])
  const [audios, setAudios] = useState([])

  const [quizRate, setQuizRate] = useState(0)
  const [statistics, setStatistics] = useState(null)

  const [selectedDepartments, setSelectedDepartments] = useState([])
  const [selectedSales, setSelectedSales] = useState([])
  const [selectedGroups, setSelectedGroups] = useState([])

  const getDepartmentList = async () => {
    const msg = await getDepartments()
    console.log('all departments', msg.data)
    const buildTreeNodes = async (departments) => {
      const findChildren = (parent) => {
        return departments.filter(department => department.parentId === parent.wxDid)
          .map(department => {
            const item: TreeDataNode = {
              key: department.wxDid,
              value: department.wxDid,
              title: department.name,
              parentId: department.parentId,
              children: findChildren(department)
            }
            return item
          })
      };
      const rootNodes = departments.filter(department => department.parentId === 0)
        .map(department => {
          const item: TreeDataNode = {
            key: department.wxDid,
            value: department.wxDid,
            title: department.name,
            parentId: department.parentId,
            children: findChildren(department)
          }
          return item
        });
      return rootNodes;
    }
    const departmentSelectData = await buildTreeNodes(msg.data);
    setDepartments(departmentSelectData)
    return departmentSelectData
  }
  const getSalesList = async (wxDids: any) => {
    const sales = []

    async function getSalesForWxDid(wxDid: any) {
      const sales = []
      const params = {
        page: 1,
        size: 9999,
      }
      if (wxDid) {
        params['wxDid'] = wxDid
      }
      const res = await getDepartmentMembers(params)
      console.log('all sales', res)
      res.data.records.forEach(sale => {
        sales.push({
          title: sale.name,
          value: sale.wxUid
        })
      })
      return sales
    }

    if (!wxDids) {
      const ss = await getSalesForWxDid();
      sales.push(...ss)
    } else {
      for (const wxDid of wxDids) {
        const ss = await getSalesForWxDid(wxDid);
        ss.forEach(s => {
          const count = sales.filter(sale => sale.value === s.value).length
          if (count === 0) {
            sales.push(s)
          }
        })
      }
    }
    setSales(sales)
  }
  const getWechatGroups = async (wxDids: any, salesWxUids: any) => {
    const wechatGroups = []

    async function getWechatGroupsForDidAndSales(wxDid: any, salesWxUid: any) {
      const wechatGroups = []
      const params = {page: 1, size: 9999}
      if (wxDid) {
        params['wxDid'] = wxDid
      }
      if (salesWxUid) {
        params['salesWxUid'] = salesWxUid
      }
      const res = await getGroups(params)
      // if (res.code !== 1) {
      //   message.error('获取微信群列表失败,' + res.msg)
      //   return
      // }
      console.log('all wechat groups', res)
      res.data.records.forEach(group => {
        wechatGroups.push({
          title: group.groupName,
          label: group.groupName,
          value: group.wxGid,
        })
      })
      return wechatGroups
    }

    if (!wxDids && !salesWxUids) {
      const gs = await getWechatGroupsForDidAndSales(null, null);
      wechatGroups.push(...gs)
    } else if (wxDids && !salesWxUids) {
      for (const wxDid of wxDids) {
        const gs = await getWechatGroupsForDidAndSales(wxDid, null);
        wechatGroups.push(...gs)
      }
    } else {
      for (const wxDid of wxDids) {
        for (const salesWxUid of salesWxUids) {
          const gs = await getWechatGroupsForDidAndSales(wxDid, salesWxUid);
          wechatGroups.push(...gs)
        }
      }
    }
    setWechatGroups(wechatGroups)
  }
  const getAudioList = async () => {
    const res = await getAllAudios({page: 1, size: 99999})
    console.log('all audios', res)
    const audios = []
    res.data.records.forEach(audio => {
      audios.push({
        title: audio.name,
        value: audio.id,
        key: audio.id,
        children: [],
      })
    })
    console.log('audios', audios)
    setAudios(audios)
  }

  useEffect(() => {
    getDepartmentList().then(res => {
      // initStatisticData()
    })
    getAudioList()
    // getSalesList(null)
    // getWechatGroups()
    setSelectedDepartments([initialState.currentUser?.wxDid])
    getSalesList([initialState.currentUser?.wxDid])
    setSelectedSales([initialState.currentUser?.wxUid])
    getWechatGroups([initialState.currentUser?.wxDid], [initialState.currentUser?.wxUid])
    setSelectedGroups([initialState.currentUser?.wxGid])
    formRef.current.setFieldsValue({
      wechatGroup: [initialState.currentUser?.wxGid]
    });

    initStatisticData({
      wxDids: [initialState.currentUser?.wxDid],
      salesWxUids: [initialState.currentUser?.wxUid],
      wechatGroupIds: [initialState.currentUser?.wxGid]
    })
  }, []);

  async function initStatisticData(data?: any) {
    let audioIds = null
    let salesWxUids = null
    let searchTimeStart = null
    let searchTimeEnd = null
    let wechatGroupIds = null
    let wxDids = null
    if (audioFormRef.current.getFieldsValue()['audio'] && audioFormRef.current.getFieldsValue()['audio'].length > 0) {
      audioIds = audioFormRef.current.getFieldsValue()['audio'].join(',')
    }
    if (formRef.current.getFieldsValue()['dateTime']) {
      searchTimeStart = formRef.current.getFieldsValue()['dateTime'][0].format('YYYY-MM-DD HH:mm:ss')
      searchTimeEnd = formRef.current.getFieldsValue()['dateTime'][1].format('YYYY-MM-DD HH:mm:ss')
    }
    if (data) {
      wxDids = data.wxDids.join(',')
      salesWxUids = data.salesWxUids.join(',')
      wechatGroupIds = data.wechatGroupIds.join(',')
    } else {
      if (selectedDepartments && selectedDepartments.length > 0) {
        wxDids = selectedDepartments.join(',')
      }
      if (selectedSales && selectedSales.length > 0) {
        salesWxUids = selectedSales.join(',')
      }
      if (selectedGroups && selectedGroups.length > 0) {
        wechatGroupIds = selectedGroups.join(',')
      }
    }
    const params: REDPACKET.RedPacketStatisticsParams = {
      audioIds: audioIds,
      salesWxUids: salesWxUids,
      searchTimeStart: searchTimeStart,
      searchTimeEnd: searchTimeEnd,
      wechatGroupIds: wechatGroupIds,
      wxDids: wxDids,
    }
    console.log('params', params)
    const res = await getRedPacketStatistics(params)
    console.log('red packet statistics', res)
    if (res.code !== 1) {
      message.error('获取红包统计失败,' + res.msg)
      setStatistics(null)
      return
    }
    setStatistics(res.data)
  }

  return (
    <PageContainer header={{title: '红包报表'}} style={{backgroundColor: '#f2f3f7'}}>
      <ProForm
        formRef={formRef}
        style={{width: '100%', backgroundColor: '#ffffff', padding: '50px'}} // 设置一个固定宽度
        // layout={'inline'}
        layout={{
          labelCol: {span: 10},
          wrapperCol: {span: 14},
        }}
        onFinish={async (values) => {
          console.log('Received values of form: ', formRef.current.getFieldsValue())
          await initStatisticData();
        }}
        onReset={() => {
          formRef.current.resetFields();
          // audioFormRef.current.resetFields();
          setSelectedDepartments([])
          setSelectedSales([])
          setSelectedGroups([])
          // setStatistics(null)
        }}
      >
        <ProForm.Group>
          <ProFormTreeSelect
            fieldProps={{
              showSearch: false,
              multiple: true,
              treeData: departments,
              treeDefaultExpandAll: true,
              value: selectedDepartments,
              onChange: (value) => {
                console.log('selected department', value)
                getSalesList(value)
                getWechatGroups(value, null)

                setSelectedDepartments(value)
                setSelectedSales([])
                setSelectedGroups([])
                // if (value.length === 0) {
                //   setSelectedSales([])
                //   setSelectedGroups([])
                // }
              }
            }}
            width='md' name={'department'} label={'门店'}/>
          <ProFormTreeSelect
            fieldProps={{
              showSearch: false,
              multiple: true,
              treeDefaultExpandAll: true,
              value: selectedSales,
              onChange: (value) => {
                console.log('selected sales', value)
                setSelectedSales(value)
                getWechatGroups(selectedDepartments, value)

                setSelectedSales(value)
                setSelectedGroups([])
                // if (value.length === 0) {
                //   setSelectedGroups([])
                // }
              },
              treeData: sales,
            }}
            width='md' name={'salesMan'} label={'销售'}/>
          <ProFormTreeSelect
            fieldProps={{
              showSearch: false,
              multiple: true,
              treeData: wechatGroups,
              treeDefaultExpandAll: true,
              value: selectedGroups,
              onChange: (value) => {
                console.log('selected wechat group', value)
                setSelectedGroups(value)
              },
            }}
            rules={[
              {
                required: true,
                message: '请选择微信群',
              },
            ]}
            width='md' name={'wechatGroup'} label={'微信群'}/>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormDateTimeRangePicker onChange={(dates: any, dateStrings: any, info: any) => {
            console.log('selected date', dateStrings)
          }} format='YYYY-MM-DD HH:mm:ss' width='md' name={'dateTime'} label={'日期'}/>

        </ProForm.Group>
      </ProForm>

      <div style={{marginTop: '50px'}}>
        <ProForm
          formRef={audioFormRef}
          style={{
            width: '100%',
            marginTop: '40px',
            justifyContent: 'center',
            alignItems: 'center',
            display: 'flex'
          }} // 设置一个固定宽度
          layout={{
            labelCol: {span: 12},
            wrapperCol: {span: 12},
          }}
          submitter={false}
        >
          <ProFormTreeSelect
            fieldProps={{
              maxTagCount: 2,
              showSearch: false,
              multiple: true,
              treeData: audios,
              treeDefaultExpandAll: true,
              onChange: (value) => {
                console.log('selected department', value)
                initStatisticData()
              }
            }}
            width='md' name={'audio'} label={'音频'}/>
        </ProForm>
        <div style={{width: '80%', margin: '40px auto 40px auto',}}>
          <Row>
            <Col span={6} style={{textAlign: 'center',}}>
              <div style={{
                width: '200px',
                height: '200px',
                borderRadius: '100px',
                backgroundColor: '#ffffff',
                justifyContent: 'center',
                alignItems: 'center',
                display: 'flex',
                fontWeight: 'bold',
              }}>
                {statistics ? statistics.quizRate : 0}%
                <br/>
                <br/>
                答题率
              </div>
            </Col>
            <Col span={12} style={{textAlign: 'center',}}>
              <div style={{
                width: '100%',
                height: '200px',
                borderRadius: '10px',
                // backgroundColor: '#ffffff',
                justifyContent: 'center',
                alignItems: 'center',
                display: 'flex',
                fontWeight: 'bold',
              }}>
                <Row style={{width: '100%'}}>
                  <Col span={8} style={{textAlign: 'center'}}>
                    <div style={{
                      width: '90%',
                      height: '200px',
                      borderRadius: '10px',
                      backgroundColor: '#ffffff',
                      justifyContent: 'center',
                      alignItems: 'center',
                      display: 'flex',
                      fontWeight: 'bold',
                      fontColor: '#6b6e88',
                      fontSize: '16px',
                      margin: '10px',
                    }}>
                      {statistics ? statistics.totalNumberOfMembers : 0}
                      <br/>
                      <br/>
                      群总人数
                      <br/>
                      (应听次数)
                    </div>
                  </Col>
                  <Col span={8} style={{textAlign: 'center'}}>
                    <div style={{
                      width: '90%',
                      height: '200px',
                      borderRadius: '10px',
                      backgroundColor: '#ffffff',
                      justifyContent: 'center',
                      alignItems: 'center',
                      display: 'flex',
                      fontWeight: 'bold',
                      fontColor: '#6b6e88',
                      fontSize: '16px',
                      margin: '10px',
                    }}>
                      {statistics ? statistics.numberOfParticipants : 0}
                      <br/>
                      <br/>
                      参与答题人数
                      <br/>
                      (已听次数)
                    </div>
                  </Col>
                  <Col span={8} style={{textAlign: 'center'}}>
                    <div style={{
                      width: '90%',
                      height: '200px',
                      borderRadius: '10px',
                      backgroundColor: '#ffffff',
                      justifyContent: 'center',
                      alignItems: 'center',
                      display: 'flex',
                      fontWeight: 'bold',
                      fontColor: '#6b6e88',
                      fontSize: '16px',
                      margin: '10px',
                    }}>
                      {statistics ? statistics.numberOfRedPacketRecipients : 0}
                      <br/>
                      <br/>
                      获得红包人数
                    </div>
                  </Col>
                </Row>
              </div>
            </Col>
            <Col span={6} style={{textAlign: 'center',}}>
              <div style={{
                width: '200px',
                height: '200px',
                borderRadius: '100px',
                backgroundColor: '#ffffff',
                justifyContent: 'center',
                alignItems: 'center',
                display: 'flex',
                marginLeft: 'auto',
                marginRight: '0',
                fontWeight: 'bold',
              }}>
                {statistics ? statistics.correctAnswerRate : 0}%
                <br/>
                <br/>
                答题正确率
              </div>
            </Col>
          </Row>
        </div>
      </div>

      <div style={{borderTop: '1px solid lightgray', marginTop: '50px'}}>
        <div style={{width: '80%', margin: '40px auto 40px auto',}}>
          <Row style={{width: '100%'}}>
            <Col span={8} style={{textAlign: 'center'}}>
              <div style={{
                width: '90%',
                height: '200px',
                borderRadius: '10px',
                backgroundColor: '#ffffff',
                justifyContent: 'center',
                alignItems: 'center',
                display: 'flex',
                fontWeight: 'bold',
                fontColor: '#6b6e88',
                fontSize: '16px',
                margin: '10px',
              }}>
                {statistics ? statistics.totalRedPacketAmount : 0}
                <br/>
                <br/>
                红包总金额
              </div>
            </Col>
            <Col span={8} style={{textAlign: 'center'}}>
              <div style={{
                width: '90%',
                height: '200px',
                borderRadius: '10px',
                backgroundColor: '#ffffff',
                justifyContent: 'center',
                alignItems: 'center',
                display: 'flex',
                fontWeight: 'bold',
                fontColor: '#6b6e88',
                fontSize: '16px',
                margin: '10px',
              }}>
                {statistics ? statistics.quizRedPacketAmount : 0}
                <br/>
                <br/>
                答题红包发放金额
              </div>
            </Col>
            <Col span={8} style={{textAlign: 'center'}}>
              <div style={{
                width: '90%',
                height: '200px',
                borderRadius: '10px',
                backgroundColor: '#ffffff',
                justifyContent: 'center',
                alignItems: 'center',
                display: 'flex',
                fontWeight: 'bold',
                fontColor: '#6b6e88',
                fontSize: '16px',
                margin: '10px',
              }}>
                {statistics ? statistics.shareRedPacketAmount : 0}
                <br/>
                <br/>
                分享红包金额
              </div>
            </Col>
          </Row>
        </div>
      </div>
    </PageContainer>
  )
}

export default RedPacketStatistics;
